package cl.uchile.sketchpad.persistance.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cl.uchile.sketchpad.persistance.model.User;

@Repository
public class UserDAOImpl implements UserDAO {

	@PersistenceContext
	private EntityManager em;

	@Override
	public User findById(Integer id) {
		return em.find(User.class, id);
	}

	@Override
	public User findByMail(String mail) {
		TypedQuery<User> query = em.createQuery("from User u where u.mail= :mail", User.class);
		query.setParameter("mail", mail.toLowerCase());
		List<User> result = query.getResultList();
		return result.size() > 0 ? result.get(0) : null;
	}

	@Override
	public User findByUsername(String username) {
		TypedQuery<User> query = em.createQuery("from User u where u.username= :username", User.class);
		query.setParameter("username", username);
		List<User> result = query.getResultList();
		return result.size() > 0 ? result.get(0) : null;
	}
	
	@Override
	@Transactional(readOnly = true)
	public List<User> getAll() {
		TypedQuery<User> q = em.createQuery("from User", User.class);
		return q.getResultList();
	}
	
	@Override
	@Transactional(readOnly = true)
	public List<User> getTVs() {
		TypedQuery<User> q = em.createQuery("from User u where u.type='" + User.Type.MONITOR.getValue() + "'", User.class);
		return q.getResultList();
	}

	@Override
	@Transactional
	public User getFenUser(String username) {
		TypedQuery<User> query = em.createQuery("from User u where u.username= :username", User.class);
		query.setParameter("username", username);
		List<User> result = query.getResultList();
		
		User user = null;
		if ( result.size() > 0 ) {
			user = result.get(0);
		} else {
			user = new User();
			user.setUsername(username);
			user.setType(User.Type.STUDENT.getValue());
			em.persist(user);
		}
		
		return user;
	}
	
	@Override
	@Transactional
	public User getGuestUser(String name, String lastName) {
		User user = new User();

		if ( name == null || "".equals(name.trim()) )
			throw new RuntimeException("Name can't be blank when creating a guest user");
		
		user.setName(name);
		user.setLastname(lastName);
		
		String username = System.currentTimeMillis() + name.replace(" ", "") + (lastName != null ? lastName.replace(" ","") : "");
		user.setUsername(username);
		user.setMail(username + "@sketchpad.guest.org");
		
		user.setType(User.Type.STUDENT.getValue());
		em.persist(user);
		
		return user;
	}

	@Override
	@Transactional
	public void persist(User user) {
		em.persist(user);
	}
	
	
}
